/*
 * Copyright 2008-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.faxsun.controller.catalog;

import com.faxsun.controller.catalog.domain.TreasureCustomer;
import com.faxsun.core.catalog.domain.FSProductImpl;
import com.faxsun.core.catalog.domain.FSSkuImpl;
import com.faxsun.core.order.service.FSOrderItemServiceImpl;
import com.faxsun.core.order.service.FSOrderService;
import com.faxsun.core.order.service.FSReferralCustomerOrderItemConstants;
import com.faxsun.core.order.service.type.FSOrderStatus;
import com.faxsun.profile.core.domain.FSCustomerImpl;
import com.faxsun.profile.core.service.FSCustomerService;
import com.faxsun.web.processor.tool.CheckMobile;
import org.apache.commons.lang3.StringUtils;
import org.broadleafcommerce.common.file.service.StaticAssetPathService;
import org.broadleafcommerce.core.catalog.domain.Product;
import org.broadleafcommerce.core.order.domain.Order;
import org.broadleafcommerce.core.order.service.OrderItemService;
import org.broadleafcommerce.core.order.service.OrderService;
import org.broadleafcommerce.core.web.controller.catalog.BroadleafProductController;
import org.broadleafcommerce.profile.core.domain.Customer;
import org.broadleafcommerce.profile.core.service.CustomerService;
import org.broadleafcommerce.profile.web.core.CustomerState;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * This class works in combination with the CategoryHandlerMapping which finds a
 * category based upon the passed in URL.
 */
@Controller("blProductController")
public class ProductController extends BroadleafProductController {

    private static final String predefinedKeywords = "范客生活,faxsun,Faxsun,FAXSUN,福克森,新奇智能,海淘正品,海外产品,智能家居,智能硬件,智能扫地机器人,智能手环,智能马桶盖,智能音箱";

    @Resource(name = "blOrderService")
    protected OrderService orderService;

    @Resource(name = "blCustomerService")
    protected CustomerService customerService;

    @Resource(name = "blStaticAssetPathService")
    protected StaticAssetPathService staticAssetPathService;

    @Resource(name = "blOrderItemService")
    protected OrderItemService orderItemService;

    private List<String> orderStatusesWithQtyCount = Arrays.asList(
        FSOrderStatus.CONFIRMED.getType()
        , FSOrderStatus.DELIVERY.getType()
        , FSOrderStatus.SINGED.getType()
//        , FSOrderStatus.SUBMITTED.getType()
    );

    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView model = super.handleRequest(request, response);

        Customer customer = CustomerState.getCustomer();

        Product product = (Product) model.getModel().get(MODEL_ATTRIBUTE_NAME);
        Long productId = product.getId();
        List<Order> orderList = ((FSOrderService) orderService).readOrderByProductId(productId);

        List<TreasureCustomer> customersForDetail = new ArrayList<TreasureCustomer>();
        for (Order orderItem : orderList) {
            TreasureCustomer tc = new TreasureCustomer();
            Date dateTime = orderItem.getSubmitDate();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            if (dateTime != null) {
                String day = df.format(dateTime);
                tc.setDate(day);
                df = new SimpleDateFormat("HH:mm:ss");
                String time = df.format(dateTime);
                tc.setTime(time);
            } else {
                tc.setDate("");
                tc.setTime("");
            }
            FSCustomerImpl fsCustomer = ((FSCustomerImpl) orderItem.getCustomer());
            String phone = fsCustomer.getMobile();
            tc.setPhone(phone);
            customersForDetail.add(tc);
        }
        Collections.sort(customersForDetail);
        model.addObject("customers", customersForDetail);
        model.addObject("isMobile", CheckMobile.check(request.getHeader("user-agent")));
        // add 优惠券显示
        model.addObject("isExistBroad", ((FSProductImpl) product).getIsBroad());
        // add for product recommendation
        model.addObject(FSReferralCustomerOrderItemConstants.REFERRAL_URL,
            getReferralURLWithReferralCode(request, customer));
        model.addObject(FSReferralCustomerOrderItemConstants.REFERRAL_IMAGE_URL, getReferralImageURL(request, product));
        // add CDN prefix for longDescription if exist
        model.addObject("processedDesc",
            staticAssetPathService.convertAllAssetPathsInContent(product.getLongDescription(), false));

        FSSkuImpl fsSku = (FSSkuImpl) product.getDefaultSku();

        model.addObject("meta_key", getKeywords(fsSku));
        model.addObject("meta_desc", fsSku.getShortDescription());

        model.addObject("orderItemQty",
            ((FSOrderItemServiceImpl) orderItemService).readOrderItemQuantitiesByProductsAndStatus(Arrays.asList(product),
                orderStatusesWithQtyCount));

        return model;
    }

    private String getKeywords(FSSkuImpl fsSku) {
        if (fsSku == null)
            return "";
        String keywords = fsSku.getProduct().getName() + "," + predefinedKeywords;
        if (!org.springframework.util.StringUtils.isEmpty(fsSku.getKeywords())) {
            keywords += "," + fsSku.getKeywords();
        }
        return keywords;
    }

    private String getReferralURLWithReferralCode(HttpServletRequest request, Customer customer) {
        return request.getRequestURL().append("?rc=")
            .append(((FSCustomerService) customerService).readOrGenerateReferralCodeForCustomer(customer))
            .toString();
    }

    private String getReferralImageURL(HttpServletRequest request, Product product) {
//        So far not working if the "asset.server.url.prefix" property not set.
//        return staticAssetPathService.convertAssetPath(
//            product.getMedia().get("primary").getUrl(), request.getContextPath(), false);

        String scheme = request.getScheme();
        String serverPort = null;
        if (("http".equalsIgnoreCase(scheme) && request.getServerPort() != 80)
            || ("https".equalsIgnoreCase(scheme) && request.getServerPort() != 443)) {
            serverPort = ":" + request.getServerPort();
        }

        return request.getScheme() + "://" + request.getServerName()
            + (StringUtils.isEmpty(serverPort) ? "" : serverPort) + request.getContextPath()
            + product.getMedia().get("primary").getUrl();
    }

}
